<!--
 * @Description: 加减签
 * @Author: wangwangwang
 * @Date: 2020-12-17 16:03:37
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-03-25 10:58:39
-->
<template>
  <el-dialog v-dialogDrag width="70%" title="加减签" :before-close="hanldeClose" :visible.sync="visible">
    <div class="form-container">
      <el-form :inline="true" :model="personTypeForm">
        <el-form-item>
          <el-input v-model="personTypeForm.person" placeholder="搜索人员"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="bottom_all" @click="searchSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="transfer-container">
      <el-row :gutter="10">
        <el-col :span="7">
          <p class="hanlde-title">选择人员:</p>
          <div class="hanlde-container">
            <el-tree ref="tree" :data="treeArry" show-checkbox class="tree-line"  :indent="0"  default-expand-all node-key="id" highlight-current :props="defaultProps"></el-tree>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="handle-submit">
            <div>
              <el-button class="bottom_all" style="margin-left:0;" @click="setSelectedData">
                <i class="el-icon-arrow-right el-icon--right" />
              </el-button>
            </div>
            <div>
              <el-button class="bottom_all" style="margin-left:0;" @click="cancleSelectedData">
                <i class="el-icon-arrow-left el-icon--left"></i>
              </el-button>
            </div>
            <!-- <div>
              <el-button class="bottom_all_two" style="margin-left:0;" @click="clearSelectedData">清空已选</el-button>
            </div> -->
          </div>
        </el-col>
        <el-col :span="13">
          <p class="hanlde-title">节点:</p>
          <div class="hanlde-container">
            <el-table border :header-cell-style="{ background: '#f3f6f9' }" style="width:100%" :data="tableData" @selection-change="handleSelectionChange">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column prop="nodeName" label="节点名称"></el-table-column>
              <el-table-column prop="userName" label="处理人">
              </el-table-column>
              <el-table-column label="状态">
                <template slot-scope="scope">
                  <span>{{(scope.row.approvalStatus === 1||!scope.row.approvalStatus)?'未审批':'已审批'}}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button class="bottom_all_two" @click="hanldeClose">取 消</el-button>
      <el-button class="bottom_all" @click="hanldeSure">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { queryPage as orgQueryPage } from "@/api/basedata/organization";
import { queryPage as userQueryPage } from "@/api/basedata/user";
import { formatTreeData } from "@/utils/utils";

export default {
  props: ["visible", 'sendTable'],
  data() {
    return {
      personTypeForm: {
        person: "",
      },
      treeArry: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
      selectedData: [],
      choisedData: [],
      allData: [],
      userList: [],
      tableData: [],
      selectData: [],
    };
  },
  watch: {
    visible(value) {
      if (value) {
        this.tableData = this.sendTable;
      }
    },
  },
  methods: {
    handleSelectionChange (rows) {
      this.selectData = rows;
    },
    /**
     * @Description: 设置已选
     * @Param:
     * @Author: wangwangwang
     */
    setSelectedData() {
      if (this.selectData.length !== 1) {
        this.$message.warning('请在右边选中一个要加签的节点')
        return
      }
      const nodeData = this.selectData[0];
      const copyData = JSON.parse(JSON.stringify(this.tableData));
      const index = copyData.findIndex(item => item.userId === nodeData.userId && nodeData.processInstanceNodeId === item.processInstanceNodeId);
      const selectPerson = this.$refs.tree.getCheckedNodes();
      const newData = selectPerson.filter(item => item.organizationId).map(item => ({userId: item.id, userName: item.name, nodeName: nodeData.nodeName,approvalStatus: 1, userType: 2,add:true, processInstanceId: nodeData.processInstanceId, processInstanceNodeId: nodeData.processInstanceNodeId}));
      /**
       * @Description: 判断相同节点是否有同一个人
       * @param {*}
       * @Author: wangwangwang
       */
      for (let i = 0; i < copyData.length; i+=1){
        for (let j = 0; j < newData.length; j+=1) {
          if (copyData[i].userId === newData[j].userId && copyData[i].processInstanceNodeId === newData[j].processInstanceNodeId) {
            this.$message.warning('相同节点下不能存在同一审批人，请确认后再提交')
            return
          }
        }
      }
      newData.unshift(index+1, 0);
      Array.prototype.splice.apply(copyData, newData);
      this.tableData = copyData;
    },
    /**
     * @Description: 取消已选
     * @Param:
     * @Author: wangwangwang
     */
    cancleSelectedData() {
      if (this.selectData.some(item => item.approvalStatus===2 || item.approvalStatus===10)) {
        this.$message.warning('已审批的节点不能删除');
        return
      }
      let maxLength = 1;
      let code = this.tableData[0].processInstanceNodeId;
      for (let i = 0; i < this.tableData.length; i+=1) {
        if (this.tableData[i].processInstanceNodeId !== code) {
          maxLength = maxLength + 1;
          code = this.tableData[i].processInstanceNodeId;
        }
      }
      const newData = this.tableData.filter((item) => !this.selectData.some((items) => (items.processInstanceNodeId === item.processInstanceNodeId && items.userId === item.userId)));
      const newData2 = newData.filter((item) => this.selectData.some(items => item.processInstanceNodeId === items.processInstanceNodeId));
      if ((newData2.length < maxLength - 2) || newData2.length === 0) {
        this.$message.warning('同一节点人员不能被全部删除');
        return
      }
      this.tableData = newData;
    },
    /**
     * @Description: 清除已选
     * @Param:
     * @Author: wangwangwang
     */
    clearSelectedData() {
      this.choisedData = [];
      this.selectedData = [];
    },
    /**
     * @Description: 获取所有组织和用户、格式化tree结构
     * @Param:
     * @Author: wangwangwang
     */
    initOrganization() {
      const params = {
        page: 1,
        pageSize: 10000,
      };
      orgQueryPage(params).then((res) => {
        if (res.code === 1001) {
          const params2 = {
            page: 1,
            pageSize: 10000,
            userEentrance: "entrance_manager",
          };
          userQueryPage(params2).then((res2) => {
            const orgList = res.data.data;
            const userList = res2.data.data;
            const newArry = userList.map((item) => ({
              ...item,
              parentId: item.organizationId,
            }));
            this.userList = userList;
            this.treeArry = formatTreeData(
              orgList.concat(newArry),
              "id",
              "parentId",
              "children",
              "parent_id"
            );
            this.allData = formatTreeData(
              orgList.concat(newArry),
              "id",
              "parentId",
              "children",
              "parent_id"
            );
          });
        }
      });
    },
    hanldeClose() {
      this.$emit("hanldeClose");
    },
    hanldeSure() {
      this.$emit("hanldeSure", this.tableData);
    },
    /**
     * @Description: 人员搜索
     * @Param: 
     * @Author: wangwangwang
     */
    searchSubmit () {
      if (this.personTypeForm.person) {
        const newData = this.userList.filter(item => item.name.indexOf(this.personTypeForm.person) > -1);
        this.treeArry = newData;
        return
      }
      this.treeArry = this.allData;
    }
  },
  mounted() {
    this.initOrganization();
  },
};
</script>
<style lang="scss" scoped>
.transfer-container {
  .hanlde-title {
    margin-bottom: 10px;
  }
  .hanlde-container {
    border-radius: 5px;
    border: 1px solid #dcdfe6;
    height: 500px;
    overflow: scroll;
    padding: 15px;
  }
}
.handle-submit {
  padding-top: 200px;
  text-align: center;
  div {
    margin: 20px 0px;
  }
}
</style>
